<?php

namespace app\admin\controller;

use think\Controller;
use think\Db;
use app\common\validate\UserValidate;

class Login extends Controller
{
	protected $datas;

	public function __construct()
	{
		if (request()->isPost()) {
			$this->datas = request()->param();
			if (empty($this->datas)) {
				$data = file_get_contents('php://input');
				$this->datas = json_decode($data, true);
			}
		} else {
			$this->datas = request()->get();
		}
	}

	/**
	 * 登录
	 * @Author   Yichen
	 * @DateTime 2020-05-03T22:00:00+0800
	 * @return   [type]                   [description]
	 */
	public function index()
	{
		if (request()->isPost()) {
			$validate = new UserValidate();
			if (!$validate->scene('login')->check($this->datas)) {
				$this->error($validate->getError());
			}
			$username = $this->datas['username'];
			$pwd = md5($this->datas['password']);
			$result = Db::name('t_system_user')->where(['username' => $username, 'password' => $pwd])->find();
			if (!$result) {
				$this->error('用户名或密码错误');
			}
			$sessionData = [
				'uid' => $result['id'],
				'username' => $result['username']
			];
			session('userInfo',$sessionData);
			$this->success('验证成功，请稍后。。。');
		}
		return $this->fetch();
	}

	/**
	 * 退出登录
	 * @Author   Yichen
	 * @DateTime 2020-05-03T22:24:18+0800
	 * @return   [type]                   [description]
	 */
	public function outLog()
	{
		session('userInfo', null);
		$this->success('退出成功');
	}
}